/*
 * Copyright © 2024-2025 Wenze Wei
 *
 * This file is part of StadionOS.
 *
 * This Source Code Form is subject to the terms of the GNU General Public License, v. 2.0.
 * You can obtain a copy of the GPL at
 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 */

#include "../include/time.h"

/**
 * @brief Convert a time_t value to a broken-down time structure based on local time.
 *
 * @param timer Pointer to a time_t value to convert.
 * @return A pointer to a Ttm structure containing the converted time.
 */
struct Ttm *Slocaltime(const time_t *timer) {
    static struct Ttm tm_info;
    time_t seconds = *timer;

    int year = 1970;
    int days_in_year;

    while (seconds >= 365 * 86400) {
        days_in_year = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365;
        seconds -= days_in_year * 86400;
        year++;
    }

    tm_info.tm_year = year - 1900;

    int month_lengths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        month_lengths[1] = 29;
    }

    tm_info.tm_mon = 0;
    while (seconds >= month_lengths[tm_info.tm_mon] * 86400) {
        seconds -= month_lengths[tm_info.tm_mon] * 86400;
        tm_info.tm_mon++;
    }

    tm_info.tm_mday = seconds / 86400 + 1;
    seconds %= 86400;

    tm_info.tm_hour = seconds / 3600;
    seconds %= 3600;
    tm_info.tm_min = seconds / 60;
    tm_info.tm_sec = seconds % 60;

    tm_info.tm_wday = (tm_info.tm_year + (tm_info.tm_year / 4) - (tm_info.tm_year / 100) + (tm_info.tm_year / 400) + (tm_info.tm_mon + 1) * 31 / 12) % 7;
    tm_info.tm_yday = (tm_info.tm_year * 365 + (tm_info.tm_year / 4) - (tm_info.tm_year / 100) + (tm_info.tm_year / 400) + tm_info.tm_mday - 1);

    tm_info.tm_isdst = 0;

    return &tm_info;
}
